//
//  RowBTCell.m
//  
//  jhf
//
//  Created by 计海峰 on 2020/7/20.
//  Copyright © 2020 jhfappkf@163.com. All rights reserved.
//

#import "RowBTCell.h"

#import "BindProtocol.h"

#import "ButtonControlM.h"
#import <CooperSDK/CooperSDK.h>

@interface RowBTCell ()

@property (nonatomic, strong) NSMutableArray <UIButton *> *btsArray;

@end

@implementation RowBTCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)btnTap:(UIButton *)btn {
    BindModel *bind = (BindModel *)self.model;
    NSArray <ButtonControlM *> *array = bind.model;
    if ([bind.model isKindOfClass:ButtonControlM.class]) {
        array = @[bind.model];
    }
    ButtonControlM *btnModel = [array safeObjectAtIndex:[self.btsArray indexOfObject:btn]];
    if (btnModel) {
        if (btnModel.method && btnModel.method.length > 0) {
            if ([btnModel isEnableTap]) {
                [bind.action run:btnModel.method any:btnModel];
            }
        }
    }
}

- (void)bindTo:(__kindof id<BindProtocol>)model; {
    
    [super bindTo:model];
    BindModel *bind = (BindModel *)model;
    NSArray <ButtonControlM *> *array = bind.model;
    if ([bind.model isKindOfClass:ButtonControlM.class]) {
        array = @[bind.model];
    }
    if (array.count > self.btsArray.count) {
        NSUInteger count = array.count - self.btsArray.count;
        for (int i = 0; i < count; i++) {
            [self.btsArray addObject:[self btn]];
        }
    }
    
    [self.btsArray enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.hidden = idx >= array.count;
    }];
    
    [array enumerateObjectsUsingBlock:^(ButtonControlM * _Nonnull config, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = self.btsArray[idx];
        [config controlBT:btn];
        // 更新按钮 frame
        btn.frame = config.frame;
        
        btn.selected = config.isSelected;
        btn.enabled = config.btEnable;
    }];
    
}

- (NSMutableArray<UIButton *> *)btsArray {
    if (!_btsArray) {
        _btsArray = [NSMutableArray array];
        [_btsArray addObject:[self btn]];
    }
    return _btsArray;
}

- (UIButton *)btn {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [btn addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgV addSubview:btn];
    return btn;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end
